package com.zcf.airobot.controller;

import com.zcf.airobot.config.Log;

import com.zcf.airobot.constants.Constants;
import com.zcf.airobot.service.ChatHistoryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;

@RequiredArgsConstructor
@RestController
@RequestMapping("/ai")
public class ChatController {

    private final ChatClient chatClient;

    private final ChatHistoryRepository chatHistoryRepository;

    // 请求方式和路径不要改动，将来要与前端联调
    @GetMapping("/chat")
    public String chat(@RequestParam(defaultValue = "讲个笑话") String prompt) {
        return chatClient
                .prompt(prompt) // 传入user提示词
                .call() // 同步请求，会等待AI全部输出完才返回结果
                .content(); //返回响应内容
    }
    /**
     * 流式返回
     */

    @Log(value = "流式返回", logFilePath = "D:\\java\\ai-robot\\src\\main\\resources\\log\\log.txt")
    @PostMapping(value = "/chat",produces = "text/html;charset=UTF-8")
    public Flux<String> chat1(@RequestParam(defaultValue = "讲个笑话") String prompt,String chatId) {


        //保存会话id
        chatHistoryRepository.save(Constants.CHAT_TYPE_KEY,chatId);
        return chatClient
                .prompt(prompt) // 传入user提示词
                .advisors(a -> a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))
                .stream().content();//流式响应
    }
}
